<script setup lang="ts">
// import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import {
  ElButton,
  ElImage,
  ElBreadcrumb,
  ElCheckbox,
  ElTabs,
  ElTabPane,
  ElContainer,
  ElScrollbar,
  ElAside,
  ElMain,
  ElHeader,
  ElTree
} from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { Table } from '@/components/Table'
import {
  sysFileListApi,
  sysFileSeeBreadcrumbApi,
  sysFileAddApi,
  sysFileEditFolderApi,
  sysFileEditFileApi,
  sysFileFolderTreeApi
} from '@/api/file'

import { useTable } from '@/hooks/web/useTableTests'
import { ref, unref, reactive, onBeforeMount } from 'vue'

import { useRoute } from 'vue-router'

import EditFolder from './components/EditFolder.vue'
import EditImg from './components/EditImg.vue'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
const dict: any = wsCache.get('dict')

const belong_type: any = dict.belong_type
const route = useRoute()
let tabValue = ref('1')
let parent_id: any = route.query.parent_id ? ref(route.query.parent_id) : ref('0')

const selectedNode: any = ref({
  id: String,
  color: String,
  fontWeight: Number
})
selectedNode.value.color = '#409EFF'
selectedNode.value.fontWeight = 900
selectedNode.value.id = '0'
const folderStorage = sessionStorage.getItem('folder_name_arr')
let folder_name_arr: any = folderStorage ? ref(JSON.parse(folderStorage)) : ref([])

const datafolderTree: any = ref([])
const getfolderTree = async () => {
  const res = await sysFileFolderTreeApi({
    my_org_id: wsCache.get('my_org_id'),
    belong_type: tabValue.value
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    datafolderTree.value = res.data
    if (tabValue.value == '1') {
      datafolderTree.value.unshift({ id: '0', parent_id: '0', name: '我的附件' })
    } else {
      datafolderTree.value.unshift({ id: '0', parent_id: '0', name: '组织附件' })
    }
  }
}
const getfolderListA = async (val) => {
  return sysFileListApi({
    belong_type: tabValue.value,
    parent_id: parent_id.value,
    pageNo: val.pageNo,
    pageSize: val.pageSize
  })
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getfolderListA,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList } = methods

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'checkbox',
    label: '选择',
    fixed: 'left',
    width: 60
  },
  {
    field: 'images',
    label: '文件',
    width: 300,
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'file_size',
    label: '文件大小',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 85,
    table: { show: true },
    search: { show: false },
    form: { show: true },
    detail: { show: false }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 180,
    table: { show: true },
    search: { show: false },
    form: {
      show: true,
      componentProps: {
        disabled: true
      }
    },
    detail: { show: false }
  }
])

const getListBreadcrumb = async () => {
  const res: any = await sysFileSeeBreadcrumbApi({
    id: parent_id.value
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    folder_name_arr.value = res.data
    if (tabValue.value == '1') {
      folder_name_arr.value.unshift({ id: '0', parent_id: '0', name: '我的附件' })
    } else {
      folder_name_arr.value.unshift({ id: '0', parent_id: '0', name: '组织附件' })
    }
    folder_name_arr.value[folder_name_arr.value.length - 1].last = '/'
  }
}

const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')
let addFolder = ref()
let imageSee = ref('')
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add_folder':
      dialogTitle.value = '新增文件夹'
      addFolder.value = row
      if (!row.belong_type) {
        addFolder.value.belong_type = tabValue.value
      }
      dialogVisible.value = true
      break
    case 'edit_folder':
      dialogTitle.value = '编辑文件夹'
      addFolder.value = row
      dialogVisible.value = true
      break
    case 'see_folder':
      dialogTitle.value = '查看文件夹'
      addFolder.value = row
      dialogVisible.value = true
      break
    case 'add_img':
      dialogTitle.value = '新增文件'
      tableObject.currentRow = row
      tableObject.currentRow.org_name = userInfo.default_org_name
      tableObject.currentRow.org_id = userInfo.default_org_id
      if (!row.belong_type) {
        tableObject.currentRow.belong_type = tabValue.value
      }
      dialogVisible.value = true
      break
    case 'edit_img':
      dialogTitle.value = '编辑文件'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'image':
      dialogTitle.value = '附件'
      imageSee.value = row.file_url
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editImgRef = ref<ComponentRef<typeof EditImg>>()
const editFolderRef = ref<ComponentRef<typeof EditFolder>>()
const loading = ref(false)

const save = async () => {
  const editFile = unref(editImgRef)
  const editFolder = unref(editFolderRef)
  switch (actionType.value) {
    case 'add_folder':
      await editFolder?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editFolder?.getFormData()) as any
          const val: any = {
            parent_id: parent_id.value,
            name: data.folder_name,
            belong_type: data.belong_type,
            is_file: '0'
          }
          let res = await sysFileAddApi(val)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
            getfolderTree()
          }
        }
      })

      break
    case 'add_img':
      await editFile?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editFile?.getFormData()) as any
          const dataFile: any = {}
          Object.assign(dataFile, data.fileData)
          dataFile.org_id = wsCache.get('my_org_id')
          dataFile.file_type = dataFile.file_type == 'image' ? '1' : '2'
          dataFile.belong_type = tabValue.value
          dataFile.is_file = '1'
          dataFile.parent_id = parent_id.value
          if (dataFile.file_type == '1') {
            dataFile.image_width = data.fileData.img_data.width
            dataFile.image_height = data.fileData.img_data.height
            dataFile.thumbnail_url = data.fileData.img_data.thumbnail_url
          }
          dataFile.name = data.file_title
          let res = await sysFileAddApi(dataFile)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
            getfolderTree()
          }
        }
      })

      break
    case 'edit_img':
      await editFile?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await editFile?.getFormData()) as any
          const dataFile: any = {}
          Object.assign(dataFile, data.fileData)
          dataFile.org_id = wsCache.get('my_org_id')
          dataFile.file_type = data.file_type.indexOf('image') !== -1 ? '2' : '1'
          dataFile.belong_type = 1
          if (dataFile.file_type == '1') {
            dataFile.image_width = data.fileData.img_data.width
            dataFile.image_height = data.fileData.img_data.height
          }
          dataFile.id = data.id
          dataFile.folder_id = data.folder_id
          dataFile.file_title = data.file_title

          let res = await sysFileEditFileApi(dataFile)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
            getfolderTree()
          }
        }
      })
      break
    case 'edit_folder':
      await editFolder?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editFolder?.getFormData()) as any
          let res = await sysFileEditFolderApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getfolderTree()
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  await getList()
  await getListBreadcrumb()
}
init()
onBeforeMount(() => {
  getfolderTree()
})
onBeforeMount(() => {
  getfolderTree()
})

const dblclick = async (a) => {
  if (a.is_file == 0) {
    parent_id.value = a.id
    selectedNode.value.id = a.id
    selectedNode.value.color = '#409EFF'
    selectedNode.value.fontWeight = 900
    getListBreadcrumb()
    getList()
  } else {
    const url = a.file_url // 打开的地址
    window.open(url)
  }
}
let selectData: any = ref([])

const changeSelect = async () => {
  selectData.value = tableObject.tableList.filter((item) => item.checkbox === true)
}

const Breadcrumb = (val) => {
  parent_id.value = val.id
  selectedNode.value.color = '#409EFF'
  selectedNode.value.fontWeight = 900
  selectedNode.value.id = val.id
  getListBreadcrumb()
  getList()
}

const handleChange = (val) => {
  tabValue.value = val
  folder_name_arr.value = []
  if (val == 1) {
    folder_name_arr.value = [{ id: '0', parent_id: '0', name: '我的附件' }]
  } else {
    folder_name_arr.value = [{ id: '0', parent_id: '0', name: '组织附件' }]
  }
  selectedNode.value.id = 0
  parent_id.value = '0'
  getList()
  getfolderTree()
}

defineExpose({
  selectData
})

const handleNodeClick = (node) => {
  selectedNode.value.color = '#409EFF'
  selectedNode.value.fontWeight = 900
  selectedNode.value.id = node.id
  parent_id.value = node.id
  getListBreadcrumb()
  getList()
}
</script>
<template>
  <ElContainer class="layout-container-demo" style="height: 500px">
    <ElAside width="230px">
      <ElTabs v-model="tabValue" class="demo-tabs" @tab-change="handleChange(tabValue)">
        <ElTabPane
          :label="item.label"
          :name="item.value"
          v-for="(item, index) in belong_type"
          :key="index"
        />
      </ElTabs>
      <ElScrollbar>
        <ElTree
          ref="treeRef"
          :data="datafolderTree"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span
              :style="{
                color: data.id == selectedNode.id ? selectedNode.color : 'inherit',
                fontWeight: data.id == selectedNode.id ? selectedNode.fontWeight : 'inherit'
              }"
            >
              {{ node.label }}
            </span>
          </template>
        </ElTree>
      </ElScrollbar>
    </ElAside>
    <ElContainer>
      <ElHeader height="">
        <div class="mb-10px">
          <ElButton type="primary" @click="action('add_folder', {})">新增文件夹</ElButton>
          <ElButton type="primary" @click="action('add_img', {})">新增文件</ElButton>
        </div>

        <ElBreadcrumb :separator-icon="ArrowRight">
          <ElBreadcrumbItem v-for="(item, i) in folder_name_arr" :key="i" @click="Breadcrumb(item)">
            {{ item.name }}
          </ElBreadcrumbItem>
        </ElBreadcrumb>
      </ElHeader>
      <ElMain>
        <Table
          v-model:pageSize="tableObject.pageSize"
          v-model:currentPage="tableObject.currentPage"
          :columns="allSchemas.tableColumns"
          :data="tableObject.tableList"
          :loading="tableObject.loading"
          :pagination="{
            total: tableObject.count
          }"
          row-key="id"
          :selection="false"
          @register="register"
          @row-dblclick="dblclick"
        >
          <template #checkbox="{ row }">
            <ElCheckbox @change="changeSelect()" v-model="row.checkbox" :disabled="!row.file_url" />
          </template>
          <template #images="{ row }">
            <div v-if="row.is_file == 1">
              <ElImage
                v-if="row.file_type == 1"
                style="width: 40px; height: 40px; border-radius: 10px"
                :src="row.file_url"
              />
              <ElImage
                v-if="row.suffix_name == 'doc' || row.suffix_name == 'docx'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.doc@3x.png"
              />
              <ElImage
                v-if="row.suffix_name == 'xls' || row.suffix_name == 'xlsx'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.sheet@3x.png"
              />
              <ElImage
                v-if="row.suffix_name == 'ppt'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.slide.png"
              />
              <ElImage
                v-if="row.suffix_name == 'file'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.folder.png"
              />
              <ElImage
                v-if="row.suffix_name == 'txt'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://img1.baidu.com/it/u=4162092432,2125414077&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=300"
              />
              <span class="span" style="padding-left: 5px">{{
                row.name + '.' + row.suffix_name
              }}</span>
            </div>
            <div v-if="row.is_file == 0">
              <Icon
                color="#E6A23C"
                icon="ion:folder-sharp"
                :size="40"
                style="border-radius: 10px"
              />
              <span class="span" style="padding-left: 5px">{{ row.name }}</span>
            </div>
          </template>
          <template #file_size="{ row }">
            <span v-if="row.is_file == 1">{{ row.file_size + `KB` }}</span>
            <span v-else></span>
          </template>
        </Table>
      </ElMain>
    </ElContainer>
  </ElContainer>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <img v-if="actionType == 'image'" w-full :src="imageSee" alt="Preview Image" />
    <EditFolder
      v-if="actionType == 'add_folder' || actionType == 'edit_folder'"
      ref="editFolderRef"
      :addFolder="addFolder"
    />
    <EditImg
      v-if="actionType == 'edit_img' || actionType == 'add_img'"
      ref="editImgRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'image' && actionType !== 'batch_shift'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<style lang="less" scoped>
.el-table td.el-table__cell div {
  display: flex;
  .span {
    line-height: 40px;
    margin-left: 10px;
  }
}
.iconButton {
  padding: 0;
  border: transparent !important;
  background-color: transparent !important;
}
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}
.layout-container-demo .el-menu {
  border-right: none;
}
.layout-container-demo .el-main {
  padding: 0;
}
.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
.menu-demo {
  display: flex;

  > div {
    width: 250px;
    margin-right: 30px;
  }
}
.layout-container-demo .el-aside,
.layout-container-demo .el-header,
.el-tabs__nav-wrap::after {
  background-color: transparent;
}
.el-table td.el-table__cell div {
  display: flex;
}
.el-card {
  color: transparent;
}

.el-header {
  height: auto;
  --el-header-height: 0;
}
.el-breadcrumb {
  line-height: 2;
}
</style>
